/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package HAVING;

import java.util.*;

/**
 *
 * @author Dung Doan
 */
public class Having {
    public Having()
    {
        
    }
    
    public Boolean hasHaving(String root)
    {
        String query = root.toUpperCase();
        if (query.indexOf("HAVING") < 0)
            return false;
        return true;
    }
    
    public String getHaving(String root)
    {
        String query = root.toUpperCase();
        int beginIndex = 0;
        int endIndex = query.indexOf("SELECT");
        if (endIndex < beginIndex)
            return null;
        beginIndex = endIndex + 6;
        
        endIndex = query.indexOf("FROM", beginIndex);
        if (endIndex < beginIndex)
            return null;
        beginIndex = endIndex + 4;
        
        endIndex = query.indexOf("WHERE", beginIndex);
        if (endIndex > beginIndex)
            beginIndex = endIndex + 5;
        
        endIndex = query.indexOf("GROUP BY", beginIndex);
        if (endIndex < beginIndex)
            return null;
        
        beginIndex = endIndex + 8;
        
        endIndex = query.indexOf("HAVING", beginIndex);
        if (endIndex < beginIndex)
            return null;
        
        beginIndex = endIndex + 6;
        
        endIndex = query.indexOf("ORDER BY", beginIndex);
        if (endIndex > beginIndex)
            return root.substring(beginIndex, endIndex).trim();
        return root.substring(beginIndex).trim();
        
    }
    public HavingType ParseHaving(String query)
    {
        
        if (hasHaving(query) == false)
            return null;
        
        String havingString = getHaving(query).trim();
        
        if (havingString.indexOf(",") >= 0)
            return null;
        HavingType ht = new HavingType(havingString);
        if (ht.isValid() == false)
            return null;
        return ht;
        
    }
}
